
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import org.apache.commons.codec.binary.Base64;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import redis.clients.jedis.Jedis;

import com.herohead.Misc;
import com.herohead.notifications.Numerous;
import com.herohead.redis.GetRedisServer;
import com.herohead.redis.RedisKeys;


public class sendClonesInQue {

	static Jedis jd;
	
	final static String listProdClonesRunning = "l_prod:clone:running";
	final static String hashProdClonesRunningName = "h_prod:clone:running:name";
	final static String slistProdClones = "z_prod:clone:";
	final static String sProdCloneProcessID = "s_prod:clone:processID";
	final static String hashProdCloneSSID = "h_prod:clone:ssid";
	final static String sProdThreadProcessID = "s_prod:thread:processID";
	final static String lProdCloneCompleted =  "s_prod:clone:completed";
	final static String hashProdThreadQueued = "h_prod:thread:queued";
	final static String hashProdThreadQueuedProcessID = "h_prod:thread:queued:processID";
	final static String listProdThreadRunning = "l_prod:thread:running";
	final static String hashProdThreadRunningProcessID =  "h_prod:thread:running:processID";
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub


		
	//	System.setProperty("http.proxyHost", "us00sprxv00.am.mt.mtnet");
//		System.setProperty("http.proxyPort", "8080");
	
 
		GetRedisServer grs = new GetRedisServer();

		String redisHostName = grs.getRedisHost();

		jd = new Jedis(redisHostName,6380);


		String lastQueued = "-1";
		String lastRunning = "-1";
		String lastSSIDClone = "-1";
		String lastQuedSize = "-1";
		String lastClonesRunning = "-1";
		String lastThreadRunningSize = "-1";

		while (true) {
 
			Long value = jd.hlen(RedisKeys.hashProdThreadQueuedProcessID);
			String v = String.valueOf(value);
			if (!v.contentEquals(lastQueued)) {
				lastQueued = v;
				try {
					System.out.println("Sending " + RedisKeys.hashProdThreadQueuedProcessID + ":" + v);
					updateValue(Numerous.numThreadsQueued,v);
					//Misc.callex("d:\\curl\\curl.exe --include --request POST -k -H \"Content-Type: application/json\" --data-binary \"{\\\"value\\\": \\\"" + v + "\\\"}\" -H \"Authorization: Basic bm1yc19PUlJWdzhqWkRIQVA6\" https://api.numerousapp.com/v1/metrics/3999603013327599947/events");
					//System.out.println(Misc.callex("d:\\curl\\curl.exe --include --request POST -k -H \"Content-Type: application/json\" --data-binary \"{\\\"value\\\": \\\"" + v + "\\\"}\" -H \"Authorization: Basic bm1yc19PUlJWdzhqWkRIQVA6\" https://api.numerousapp.com/v1/metrics/3999603013327599947/events"));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				System.out.println("Nothing changed for " + RedisKeys.hashProdThreadQueuedProcessID);
			}
			value = jd.llen(listProdThreadRunning);
			v = String.valueOf(value);
			if (!v.contentEquals(lastRunning)) {
				lastRunning = v;
				try {
					System.out.println("Sending " + listProdThreadRunning + ":" + v);
					updateValue(Numerous.numThreadsRunning,v);
					//Misc.callex("d:\\curl\\curl.exe --include --request POST -k -H \"Content-Type: application/json\" --data-binary \"{\\\"value\\\": \\\"" + v + "\\\"}\" -H \"Authorization: Basic bm1yc19PUlJWdzhqWkRIQVA6\" https://api.numerousapp.com/v1/metrics/2029967973232833524/events");
					//System.out.println(Misc.callex("d:\\curl\\curl.exe --include --request POST -k -H \"Content-Type: application/json\" --data-binary \"{\\\"value\\\": \\\"" + v + "\\\"}\" -H \"Authorization: Basic bm1yc19PUlJWdzhqWkRIQVA6\" https://api.numerousapp.com/v1/metrics/2029967973232833524/events"));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				System.out.println("Nothing changed for " + listProdThreadRunning);
			}
			
			value = jd.scard("s_prod:ssid:not:cloned");
			v = String.valueOf(value);
			if (!v.contentEquals(lastSSIDClone)) {
				lastSSIDClone = v;
				try {
					System.out.println("Sending s_prod:ssid:not:cloned " + v);
					updateValue(Numerous.SSIDNotCloned,v);
					//Misc.callex("d:\\curl\\curl.exe --include --request POST -k -H \"Content-Type: application/json\" --data-binary \"{\\\"value\\\": \\\"" + v + "\\\"}\" -H \"Authorization: Basic bm1yc19PUlJWdzhqWkRIQVA6\" https://api.numerousapp.com/v1/metrics/7234825922801515336/events");
					//System.out.println(Misc.callex("d:\\curl\\curl.exe --include --request POST -k -H \"Content-Type: application/json\" --data-binary \"{\\\"value\\\": \\\"" + v + "\\\"}\" -H \"Authorization: Basic bm1yc19PUlJWdzhqWkRIQVA6\" https://api.numerousapp.com/v1/metrics/2029967973232833524/events"));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				System.out.println("Nothing changed for s_prod:ssid:not:cloned");
			}
			
			String size = getSize(hashProdThreadQueuedProcessID);
			//v = String.valueOf(value);
			if (!size.contentEquals(lastQuedSize)) {
				lastQuedSize = size;
				try {
					
					
					System.out.println("Sending " + hashProdThreadQueuedProcessID + ":" + size);
					updateValue(Numerous.sizeThreadsQueued,size);
					
					
					//Misc.callex("d:\\curl\\curl.exe --include --request POST -k -H \"Content-Type: application/json\" --data-binary \"{\\\"value\\\": \\\"" + size + "\\\"}\" -H \"Authorization: Basic bm1yc19PUlJWdzhqWkRIQVA6\" https://api.numerousapp.com/v1/metrics/3824470437759974141/events");
					//System.out.println(Misc.callex("d:\\curl\\curl.exe --include --request POST -k -H \"Content-Type: application/json\" --data-binary \"{\\\"value\\\": \\\"" + v + "\\\"}\" -H \"Authorization: Basic bm1yc19PUlJWdzhqWkRIQVA6\" https://api.numerousapp.com/v1/metrics/2029967973232833524/events"));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				System.out.println("Nothing changed for prod:threads:queued:processID");
			}
			
			
			
			String runningSize = getSize(hashProdThreadRunningProcessID);
			//v = String.valueOf(value);
			if (!runningSize.contentEquals(lastThreadRunningSize)) {
				lastThreadRunningSize = runningSize;
				try {
					System.out.println("Sending " + hashProdThreadRunningProcessID + ":" +runningSize);
					updateValue(Numerous.sizeThreadsRunning,runningSize);
					//Misc.callex("d:\\curl\\curl.exe --include --request POST -k -H \"Content-Type: application/json\" --data-binary \"{\\\"value\\\": \\\"" + runningSize + "\\\"}\" -H \"Authorization: Basic bm1yc19PUlJWdzhqWkRIQVA6\" https://api.numerousapp.com/v1/metrics/6438743454896415416/events");
					//System.out.println(Misc.callex("d:\\curl\\curl.exe --include --request POST -k -H \"Content-Type: application/json\" --data-binary \"{\\\"value\\\": \\\"" + v + "\\\"}\" -H \"Authorization: Basic bm1yc19PUlJWdzhqWkRIQVA6\" https://api.numerousapp.com/v1/metrics/2029967973232833524/events"));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				System.out.println("Nothing changed for " +  hashProdThreadRunningProcessID);
			}
			
			
			String cloneRunning = String.valueOf(jd.llen(listProdClonesRunning));
			//v = String.valueOf(value);
			if (!cloneRunning.contentEquals(lastClonesRunning)) {
				lastClonesRunning = cloneRunning;
				try {
					System.out.println("Sending " + listProdClonesRunning + ":" +cloneRunning);
					updateValue(Numerous.numClonesRunning,cloneRunning);
					//Misc.callex("d:\\curl\\curl.exe --include --request POST -k -H \"Content-Type: application/json\" --data-binary \"{\\\"value\\\": \\\"" + cloneRunning + "\\\"}\" -H \"Authorization: Basic bm1yc19PUlJWdzhqWkRIQVA6\" https://api.numerousapp.com/v1/metrics/4019759641789911230/events");
					//System.out.println(Misc.callex("d:\\curl\\curl.exe --include --request POST -k -H \"Content-Type: application/json\" --data-binary \"{\\\"value\\\": \\\"" + v + "\\\"}\" -H \"Authorization: Basic bm1yc19PUlJWdzhqWkRIQVA6\" https://api.numerousapp.com/v1/metrics/2029967973232833524/events"));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				System.out.println("Nothing changed for " +  listProdClonesRunning);
			}
			
			
			//updateDescription(Numerous.numClonesRunning,"Test:sds:Sfsfsfsf:sdfsfs");
			
			
			
			
			
			
			try {
				Thread.sleep(50000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		/**	
		Misc m = new Misc();

		System.out.println("d:\\curl\\curl.exe --include --request POST -k -H \"Content-Type: application/json\" --data-binary \"{\\\"value\\\": \\\"911\\\"}\" -H \"Authorization: Basic bm1yc19PUlJWdzhqWkRIQVA6\" https://api.numerousapp.com/v1/metrics/3999603013327599947/events");

		try {
			System.out.println(Misc.callex("d:\\curl\\curl.exe --include --request POST -k -H \"Content-Type: application/json\" --data-binary \"{\\\"value\\\": \\\"211\\\"}\" -H \"Authorization: Basic bm1yc19PUlJWdzhqWkRIQVA6\" https://api.numerousapp.com/v1/metrics/3999603013327599947/events"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		 **/
	}
	
	@SuppressWarnings("rawtypes")
	public static String getSize (String hash) {

		long size = 0;
		long s1 = 0;

		Map<String, String> mp = jd.hgetAll(hash);
		Misc m = new Misc();
		Iterator it = mp.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry pairs = (Map.Entry)it.next();
			//System.out.println(pairs.getKey() + " = " + pairs.getValue());
			String temp = pairs.getValue().toString();
			size = size + Long.parseLong(temp);
			
			//s1 = s1 + Long.parseLong(m.bytesToMB(temp));
			
			//System.out.println("key = " +pairs.getKey().toString());
			//System.out.println("value = " +pairs.getValue().toString());
			
			
		}

		

		//System.out.println("Total size : " + String.valueOf(size));
		//System.out.println("Total size (new) : " + String.valueOf(s1));
		
		String s = m.bytesToMB(String.valueOf(size));

		return s;
	}

	@SuppressWarnings("unchecked")
	public static void updateDescription (String appkey,String value) {
	
		

		byte[] encodedBytes = Base64.encodeBase64(Numerous.numeroiusapiUser.getBytes());
		String userAuth =  new String(encodedBytes);
		
		
		try {

			//String url = "https://api.numerousapp.com/v1/metrics/" + appkey + "/events";
			String url = "https://api.numerousapp.com/v1/metrics/" + appkey;
			//String url = "https://api.numerousapp.com/v1/users/2088622069300404688/metrics";
			URL obj = new URL(url);
			HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
			con.setRequestProperty("Authorization", "Basic " + userAuth);
			con.setRequestProperty("Content-Type", "application/json");
			con.setRequestMethod("PUT");
			con.usingProxy();
			con.setDoOutput(true);


			JSONObject jobj = new JSONObject();
			//jobj.put("value", value);
			jobj.put("description", value);
			//jobj.put("units", "kgs");

			System.out.println(jobj.toJSONString());
			//System.out.println(jobj.toString());

			//System.exit(0);

			String data = jobj.toJSONString();

			//String data =  "{\"value\":\"99\"}";
			OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
			out.write(data);
			out.close();

			// new InputStreamReader(con.getInputStream());

			BufferedReader in = new BufferedReader(
					new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();
			System.out.println(response.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}


	}
	
	
	public static void updateValue (String appkey,String value) {
		
		
		
		try {

			byte[] encodedBytes = Base64.encodeBase64(Numerous.numeroiusapiUser.getBytes());
			String userAuth =  new String(encodedBytes);
			
			
			String url = "https://api.numerousapp.com/v1/metrics/" + appkey + "/events";
			//String url = "https://api.numerousapp.com/v1/metrics/2088622069300404688";
			//String url = "https://api.numerousapp.com/v1/users/2088622069300404688/metrics";
			URL obj = new URL(url);
			HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
			con.setRequestProperty("Authorization", "Basic " + userAuth);
			con.setRequestProperty("Content-Type", "application/json");
			con.setRequestMethod("POST");
			con.usingProxy();
			con.setDoOutput(true);

			JSONObject jobj = new JSONObject();
			jobj.put("value", value);
			//jobj.put("description", "cool it works - again");
			//jobj.put("units", "kgs");

			//System.out.println(jobj.toJSONString());
			//System.out.println(jobj.toString());

			//System.exit(0);

			String data = jobj.toJSONString();

			//String data =  "{\"value\":\"99\"}";
			OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
			out.write(data);
			out.close();

			// new InputStreamReader(con.getInputStream());

			BufferedReader in = new BufferedReader(
					new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();
			//System.out.println(response.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}


	}

	public static JSONArray getAllValues (String appkey) {
		
		String ret = null;
		
		
		try {

			byte[] encodedBytes = Base64.encodeBase64(Numerous.numeroiusapiUser.getBytes());
			String userAuth =  new String(encodedBytes);
			
			
			String url = "https://api.numerousapp.com/v1/users/" + appkey + "/metrics";
			//String url = "https://api.numerousapp.com/v1/users/metrics";
			//String url = "https://api.numerousapp.com/v1/metrics/2088622069300404688";
			//String url = "https://api.numerousapp.com/v1/users/2088622069300404688/metrics";
			//String url = "https://api.numerousapp.com/v1/metrics/3999603013327599947/events";
			URL obj = new URL(url);
			HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
			con.setRequestProperty("Authorization", "Basic " + userAuth);
			con.setRequestProperty("Content-Type", "application/json");
			con.setRequestMethod("GET");

			con.setDoOutput(true);

			JSONObject jobj = new JSONObject();
			jobj.put("value", "0");
			//jobj.put("description", "cool it works - again");
			//jobj.put("units", "kgs");

			String data = jobj.toJSONString();

			con.getContent();
			//OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
			//out.write("");
			//out.close();

			// new InputStreamReader(con.getInputStream());

			BufferedReader in = new BufferedReader(
					new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();
			ret = response.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		JSONArray jo = getJsonArray(ret);
		return jo;

	}

	public static JSONObject getJsonObject(String json){
		JSONParser parser = new JSONParser();
		Object obj1 = null;
		try {
			obj1 = parser.parse(json);
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			obj1 = parser.parse(json);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return (JSONObject) obj1;
	}
	
	public static JSONArray getJsonArray(String json){
		JSONParser parser = new JSONParser();
		Object obj1 = null;
		try {
			obj1 = parser.parse(json);
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			obj1 = parser.parse(json);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return (JSONArray) obj1;
	}
	
	
}
